R Functions Exercises

Let's test your knowledge of functions in R! For these exercisee you be given instructions to create functions that take in certain inputs and give certain outputs. Just follow any instructions written in bold below. The first two are examples done for you.


EXAMPLE 1: Create a function that takes in a name as a string argument, and prints out "Hello name"

In [7]:
hello_you <- function(name){
    print(paste('Hello',name))
}
In [6]:
hello_you('Sam')
[1] "Hello  Sam"

EXAMPLE 2: Create a function that takes in a name as a string argument and returns a string of the form - "Hello name"

In [8]:
In [10]:
print(hello_you2('Sam'))
[1] "Hello Sam"

Ex 1: Create a function that will return the product of two integers.

In [12]:
In [13]:
prod(3,4)
Out[13]:
12

Ex 2: Create a function that accepts two arguments, an integer and a vector of integers. It returns TRUE if the integer is present in the vector, otherwise it returns FALSE. Make sure you pay careful attention to your placement of the return(FALSE) line in your function!

In [15]:
In [17]:
num_check(2,c(1,2,3))
Out[17]:
TRUE
In [20]:
num_check(2,c(1,4,5))
Out[20]:
FALSE

Ex 3: Create a function that accepts two arguments, an integer and a vector of integers. It returns the count of the number of occurences of the integer in the input vector.

In [24]:
In [25]:
num_count(2,c(1,1,2,2,3,3))
Out[25]:
2
In [26]:
num_count(1,c(1,1,2,2,3,1,4,5,5,2,2,1,3))
Out[26]:
4

Ex 4: We want to ship bars of aluminum. We will create a function that accepts an integer representing the requested kilograms of aluminum for the package to be shipped. To fullfill these order, we have small bars (1 kilogram each) and big bars (5 kilograms each). Return the least number of bars needed.

For example, a load of 6 kg requires a minimum of two bars (1 5kg bars and 1 1kg bars). A load of 17 kg requires a minimum of 5 bars (3 5kg bars and 2 1kg bars).

In [37]:
In [39]:
bar_count(6)
Out[39]:
2
In [45]:
bar_count(17)
Out[45]:
5

Ex 5: Create a function that accepts 3 integer values and returns their sum. However, if an integer value is evenly divisible by 3, then it does not count towards the sum. Return zero if all numbers are evenly divisible by 3. Hint: You may want to use the append() function.

In [54]:
In [56]:
summer(7,2,3)
Out[56]:
9
In [57]:
summer(3,6,9)
Out[57]:
0
In [58]:
summer(9,11,12)
Out[58]:
11

Ex 6: Create a function that will return TRUE if an input integer is prime. Otherwise, return FALSE. You may want to look into the any() function. There are many possible solutions to this problem.

In [59]:
In [60]:
prime_check(2)
Out[60]:
TRUE
In [61]:
prime_check(5)
Out[61]:
TRUE
In [62]:
prime_check(4)
Out[62]:
FALSE
In [63]:
prime_check(237)
Out[63]:
FALSE
In [65]:
prime_check(131)
Out[65]:
TRUE

Great Job!